package br.fbv.cryptosvault.view;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TableLayout;
import br.fbv.cryptosvault.R;
import br.fbv.cryptosvault.core.SoundManager;
import br.fbv.cryptosvault.model.account.AccountManager;
import br.fbv.cryptosvault.model.exception.InvalidEmailException;
import br.fbv.cryptosvault.model.exception.InvalidPasswordException;
import br.fbv.cryptosvault.model.util.Constants;
import br.fbv.cryptosvault.model.util.Util;

public class RegisterActivity extends Activity implements OnClickListener, OnFocusChangeListener {
	
    private static final InputFilter noInputFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start,
                int end, Spanned dest, int dstart, int dend) {
            return "";
        }
    };
	
	private AccountManager accountManager;
	private SoundManager soundManager;
	private EditText edtEmail;
	private EditText edtPassword;
	private Button btnRegister;
	private TableLayout keyboard;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		soundManager = SoundManager.getInstance(this);
		accountManager = AccountManager.getInstance(this);
		setContentView(R.layout.register_screen);
		
		edtEmail = (EditText) findViewById(R.id.EdtRegisterEmail);
		edtPassword = (EditText) findViewById(R.id.EdtRegisterPassword);
		btnRegister = (Button) findViewById(R.id.btnRegister);
		keyboard = (TableLayout) findViewById(R.id.keyboard);
	}
	
	@Override
	protected void onStart() {
		edtPassword.setOnFocusChangeListener(this);
		btnRegister.setOnClickListener(this);
		
		keyboard.setVisibility(View.INVISIBLE);
		
		configPassKeyboard(this);
		Util.disableShowVirtualKeyboard(edtPassword);
		Util.disableUserInputs(edtPassword);
		super.onStart();
	}
	
	@Override
	protected void onDestroy() {
		accountManager = null;
		super.onDestroy();
	}
	
	@Override
	public void onBackPressed() {
		setResult(RESULT_CANCELED);
		super.onBackPressed();
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btnRegister) {
			try {
				accountManager.registerAccount(edtEmail.getText().toString(), edtPassword.getText().toString());
				setResult(RESULT_OK);
				finish();
			} catch (InvalidEmailException e) {
				Util.showDialog(R.string.error_title,
								R.drawable.error_icon, 
								R.string.invalid_email, 
								R.string.ok_label, 
								this);
				e.printStackTrace();
			} catch (InvalidPasswordException e) {
				Util.showDialog(R.string.error_title,
						R.drawable.error_icon, 
						R.string.invalid_password, 
						R.string.ok_label, 
						this);
				e.printStackTrace();
			}
		}
	}
	
	public void configPassKeyboard(Activity activity) {
		ImageButton btnCancel = (ImageButton) activity.findViewById(R.id.btn_cancel_password);
		btnCancel.setVisibility(View.INVISIBLE);
		ImageButton btnConfirm = (ImageButton) activity.findViewById(R.id.btn_confirm_password);
		btnConfirm.setVisibility(View.INVISIBLE);
		ViewGroup keyboardRow1 = (ViewGroup) activity.findViewById(R.id.keypadRow1);
		setKeyboardRowClick(keyboardRow1, activity);
		ViewGroup keyboardRow2 = (ViewGroup) activity.findViewById(R.id.keypadRow2);
		setKeyboardRowClick(keyboardRow2, activity);
		ViewGroup keyboardRow3 = (ViewGroup) activity.findViewById(R.id.keypadRow3);
		setKeyboardRowClick(keyboardRow3, activity);
		ViewGroup keyboardRow4 = (ViewGroup) activity.findViewById(R.id.keypadRow4);
		setKeyboardRowClick(keyboardRow4, activity);
	}
	
    /**
     * Ativa linha do teclado para tratamento de clicks
     * @param row
     * @param activity
     */
	private void setKeyboardRowClick(ViewGroup row, final Activity activity) {
		for (int i = 0; i < row.getChildCount(); i++) {
			row.getChildAt(i).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {

					View currentFocus = activity.getCurrentFocus();

					if (currentFocus != null && currentFocus instanceof EditText) {
						EditText edit = (EditText) currentFocus;

						if (edit.getInputType() == InputType.TYPE_CLASS_TEXT
								+ InputType.TYPE_TEXT_VARIATION_PASSWORD) {

							soundManager.stopSounds();
							soundManager.playSound(SoundManager.DIGIT);

							if (edit.getText().length() < Constants.PASSWORD_MAX_LENGTH) {
								edit.setFilters(new InputFilter[] {});
								String key = (String) view.getTag();
								edit.getText().append(key);
								edit.setFilters(new InputFilter[] { noInputFilter });
							}
							if (edit.getText().length() == Constants.PASSWORD_MAX_LENGTH) {
								View nextFocus = currentFocus.focusSearch(View.FOCUS_DOWN);
								if (nextFocus != null) {
									nextFocus.requestFocus();
								}
							}
						}
					}
				}
			});
		}
	}

	@Override
	public void onFocusChange(View view, boolean hasFocus) {
		if(view.getId() == R.id.EdtRegisterPassword && hasFocus){
			keyboard.setVisibility(View.VISIBLE);
		}
		else if (view.getId() == R.id.EdtRegisterPassword && !hasFocus){
			keyboard.setVisibility(View.INVISIBLE);
		}
	}
}
